import { nextTick } from 'vue'
import { createI18n, I18n } from 'vue-i18n'
import zhlang from '@/assets/lang/zh.json'
import langArr from '@/utils/lang'

const lang = process.env.VUE_APP_I18N_LOCALE || 'zh'
let i18n:I18n<unknown, unknown, unknown, true>
type setupI18nTypes = () => I18n<unknown, unknown, unknown, true>
console.log(lang, 2342342)
export const setupI18n:setupI18nTypes = () => {
  i18n = createI18n({
    locale: lang,
    messages: { [lang]: zhlang }
  })
  if (lang !== 'zh') {
    loadLocaleMessages(lang)
  }
  setI18nLanguage(lang)
  return i18n
}
type setI18nLanguageTypes = (locale:string) =>void
export const setI18nLanguage:setI18nLanguageTypes = (locale) => {
  i18n.global.locale = locale
  /**
   * NOTE:
   * If you need to specify the language setting for headers, such as the `fetch` API, set it here.
   * The following is an example for axios.
   *
   * axios.defaults.headers.common['Accept-Language'] = locale
   */
  const htmlEl = document.querySelector('html')
  if (htmlEl !== null) {
    htmlEl.setAttribute('lang', locale)
  }
}

// 异步加载
export const loadLocaleMessages = async (locale: string):Promise<void> => {
  if (langArr.indexOf(lang) > -1) {
    // load locale messages with dynamic import
    const messages = await import(
      /* webpackChunkName: "locale-[request]" */ `@/assets/lang/${locale}.json`
    )
    // set locale and locale message
    i18n.global.setLocaleMessage(locale, messages.default)
    setI18nLanguage(locale)
  }

  return nextTick()
}
